<!-- 用户管理 -->
<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-input
          clearable
          v-model="searchForm.username"
          placeholder="用户名"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain @click="getUserList">搜索</el-button>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          @click="dialogVisible = true"
          v-if="hasAuth('sys:user:save')"
          >新增</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button
          type="danger"
          @click="deleteHandle(null)"
          :disabled="delStatus"
          >批量删除</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <el-table
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      border
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>

      <el-table-column label="头像" width="50">
        <template slot-scope="scope">
          <el-avatar size="small" :src="scope.row.avatar"></el-avatar>
        </template>
      </el-table-column>

      <el-table-column prop="username" label="用户名" width="120">
      </el-table-column>
      <el-table-column prop="code" label="角色名称">
        <template slot-scope="scope">
          <el-tag
            size="small"
            type="info"
            v-for="(item, index) in scope.row.roleIds"
            :key="index"
            >{{ item }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱"> </el-table-column>
      <el-table-column prop="phone" label="手机号"> </el-table-column>

      <el-table-column prop="statu" label="状态" width="150">
        <template slot-scope="scope">
          <el-tag size="small" v-if="scope.row.statu === 1" type="success"
            >正常</el-tag
          >
          <el-tag size="small" v-else-if="scope.row.statu === 0" type="danger"
            >禁用</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="created" width="200" label="创建时间">
      </el-table-column>
      <el-table-column prop="icon" label="操作" width="273">
        <template slot-scope="scope">
          <el-button type="text" @click="roleHandle(scope.row.id)"
            >分配角色</el-button
          >
          <el-divider direction="vertical"></el-divider>

          <el-button
            type="text"
            @click="repassHandle(scope.row.id, scope.row.username)"
            >重置密码</el-button
          >
          <el-divider direction="vertical"></el-divider>

          <el-button type="text" @click="editHandle(scope.row.id)"
            >编辑</el-button
          >
          <el-divider direction="vertical"></el-divider>
          <el-button type="text" @click="deleteHandle(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 50, 100]"
      :current-page="currPage"
      :page-size="pageSize"
      :total="totalCount"
    >
    </el-pagination>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="roleDialogFormVisible"
      width="600px"
      :before-close="roleDialogFormClose"
    >
      <el-form :model="roleForm">
        <el-tree
          :data="roleTreeData"
          show-checkbox
          ref="roleTree"
          :check-strictly="checkStrictly"
          node-key="id"
          :default-expand-all="true"
          :props="defaultProps"
        >
        </el-tree>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="roleDialogForm">取 消</el-button>
        <el-button type="primary" @click="submitRoleHandle('roleForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!--新增对话框-->
    <el-dialog
      title="新增用户"
      :visible.sync="dialogVisible"
      width="600px"
      :before-close="handleClose"
    >
      <el-form :model="editForm" :rules="editFormRules" ref="editForm">
        <el-form-item label="用户名" prop="username" label-width="100px">
          <el-input v-model="editForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" label-width="100px">
          <el-input v-model="editForm.password" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email" label-width="100px">
          <el-input v-model="editForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone" label-width="100px">
          <el-input v-model="editForm.phone" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="状态" prop="statu" label-width="100px">
          <el-radio-group v-model="editForm.statu">
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="1">正常</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('editForm')">取 消</el-button>
        <el-button type="primary" @click="submitForm('editForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!--修改对话框-->
    <el-dialog
      title="修改用户"
      :visible.sync="dialogUpdateVisible"
      width="600px"
      :before-close="handleClose"
    >
      <el-form :model="editForm" :rules="editFormRules" ref="editForm">
        <el-form-item label="用户名" prop="username" label-width="100px">
          <el-input v-model="editForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <!-- <el-form-item label="密码" prop="password" label-width="100px">
          <el-input v-model="editForm.password" autocomplete="off"></el-input>
        </el-form-item> -->

        <el-form-item label="邮箱" prop="email" label-width="100px">
          <el-input v-model="editForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone" label-width="100px">
          <el-input v-model="editForm.phone" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="状态" prop="statu" label-width="100px">
          <el-radio-group v-model="editForm.statu">
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="1">正常</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('editForm')">取 消</el-button>
        <el-button type="primary" @click="submitForm('editForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件(比如:组件、工具js、)
//例如：import 组件名 from '组件路径'
export default {
  //import引入的组件需要注入到对象中才能使用
  data() {
    return {
      totalCount: 0,
      pageSize: 10,
      currPage: 1,
      totalPage: 1,
      input: "",
      delStatus: true,
      checkStrictly: true,
      dialogVisible: false,
      roleDialogFormVisible: false,
      dialogUpdateVisible: false,
      tableData: [],
      roleTreeData: [],
      searchForm: {
        username: ""
      },
      editForm: {},
      roleForm: {},
      defaultProps: {
        children: "children",
        label: "name"
      },
      editFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        statu: [{ required: true, message: "请选择状态", trigger: "blur" }]
      }
    };
  },

  components: {},

  computed: {},

  // mounted: {},

  methods: {
    repassHandle(id, username) {
      this.$confirm(
        "将重置用户【" + username + "】的密码, 是否继续? 默认密码:111111",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        this.$http.post("/sys/user/reset/pass", id).then(res => {
          this.$message({
            showClose: true,
            message: "恭喜你，操作成功",
            type: "success",
            onClose: () => {}
          });
        });
      });
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          done();
          this.resetForm("editForm");
        })
        .catch(_ => {});
    },
    roleDialogFormClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          this.$refs.roleTree.setCheckedKeys([]);
          done();
          this.resetForm("roleForm");
        })
        .catch(_ => {});
    },
    roleDialogForm() {
      this.roleDialogFormVisible = false;
      this.$refs.roleTree.setCheckedKeys([]);
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialogVisible = false;
      this.editForm = {};
      this.roleForm = {};
    },
    handleSelectionChange() {},
    getUserList() {
      this.$http
        .get("/sys/user/list", {
          params: {
            username: this.searchForm.username,
            currPage: this.currPage,
            pageSize: this.pageSize
          }
        })
        .then(res => {
          this.tableData = res.data.data.list;
          this.pageSize = res.data.data.pageSize;
          this.currPage = res.data.data.currPage;
          this.totalCount = res.data.data.totalCount;
        });
    },
    roleHandle(id) {
      this.roleDialogFormVisible = true;
      // alert(id);
      this.$http.get("/sys/user/info/" + id).then(res => {
        this.roleForm = res.data.data;
        console.log(res.data.data);
        // console.log("roleForm", this.roleForm);
        // console.log("分配角色", res.data.data.roles);

        let roleIdsList = [];
        res.data.data.roleIds.forEach(item => {
          roleIdsList.push(item);
        });
        console.log("roleIds", roleIdsList);

        this.$refs.roleTree.setCheckedKeys(roleIdsList);
      });
    },
    editHandle(id) {
      this.$http.get("/sys/user/info/" + id).then(res => {
        this.editForm = res.data.data;

        this.dialogUpdateVisible = true;
      });
    },
    serachRoleList() {},
    deleteHandle(id) {
      let ids = [];
      console.log("id", id);
      if (id) {
        ids.push(id);
      } else {
        this.multipleSelection.forEach(item => {
          ids.push(item.id);
        });
      }

      this.$confirm("删除当前选中的角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http.post("/sys/user/delete/", ids).then(res => {
            this.$message({
              type: "success",
              message: "删除成功!",
              onClose: () => {
                //更新成功后 刷新菜单列表
                this.getUserList();
              }
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val;
      this.getUserList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.current = val;
      this.getUserList();
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$http
            .post(
              "/sys/user/" + (this.editForm.id ? "update" : "save"),
              this.editForm
            )
            .then(res => {
              this.$message({
                showClose: true,
                message: "恭喜你，操作成功",
                type: "success",
                onClose: () => {
                  this.getUserList();
                }
              });
              this.$refs[formName].resetFields();
              this.dialogVisible = false;
              this.dialogUpdateVisible = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    submitRoleHandle(formName) {
      var roleIds = this.$refs.roleTree.getCheckedKeys();

      console.log(roleIds);

      this.$http
        .post("/sys/user/distribution/role/user/" + this.roleForm.id, roleIds)
        .then(res => {
          this.$message({
            showClose: true,
            message: "操作成功",
            type: "success",
            onClose: () => {
              this.getUserList();
            }
          });

          this.roleDialogFormVisible = false;
        });
    },
    //多选框
    handleSelectionChange(val) {
      console.log("handleSelectionChange:", val);
      this.multipleSelection = val;

      //激活批量删除
      this.delStatus = val.length === 0;
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getUserList();

    this.$http.get("/sys/role/list").then(res => {
      this.roleTreeData = res.data.data.list;
    });
  }
};
</script>
<style scoped>
.el-pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
